

#import "SectionsViewController.h"
#import <SMS_SDK/SMS_SDK.h>
#import "CTHeader.h"
#import "CTAppLanguage.h"
#import "UIViewAdditions.h"
#import "CTLoginView_Def.h"

@interface SectionsViewController ()
{
    NSMutableData*_data;
    int _state;
    NSString* _duid;
    NSString* _token;
    NSString* _appKey;
    NSString* _appSecret;
    NSMutableArray* _areaArray;
    UIView *topView;
}

@end


@implementation SectionsViewController
@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize search;
@synthesize allNames;

#pragma mark -
#pragma mark Custom Methods
- (void)resetSearch
{
    NSMutableDictionary *allNamesCopy = [self mutableDeepCopy:allNames];
    self.names = allNamesCopy;
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys] 
                                   sortedArrayUsingSelector:@selector(compare:)]];
    self.keys = keyArray;
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    [self resetSearch];
    
    for (NSString *key in self.keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];
        for (NSString *name in array) {
            if ([name rangeOfString:searchTerm 
                            options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:key];
        [array removeObjectsInArray:toRemove];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [table reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor=CT_HEADER_ORANGE_COLOR;
    [self createThirtPartyTitleView];
//    CGFloat statusBarHeight=0;
//    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0)
//    {
//        statusBarHeight=20;
//    }
//    
//    UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0+statusBarHeight, self.view.frame.size.width, 44)];
//    UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:nil];
//    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"back", nil)
//                                                                   style:UIBarButtonItemStyleBordered
//                                                                  target:self
//                                                                  action:@selector(clickLeftButton)];
//
//    [navigationItem setTitle:NSLocalizedString(@"countrychoose", nil)];
//    [navigationBar pushNavigationItem:navigationItem animated:NO];
//    [navigationItem setLeftBarButtonItem:leftButton];
//    [self.view addSubview:navigationBar];
    
    search=[[UISearchBar alloc] init];
    search.frame=CGRectMake(0, topView.bottom, self.view.frame.size.width, 44);
    [self.view addSubview:search];
    
    table=[[UITableView alloc] initWithFrame:CGRectMake(0, search.bottom, self.view.frame.size.width, CT_HEADER_SCREEN_HEIGHT-topView.height-search.height) style:UITableViewStylePlain];
    [self.view addSubview:table];

    table.dataSource=self;
    table.delegate=self;
    search.delegate=self;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"country"
                                                     ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] 
                          initWithContentsOfFile:path];
    self.allNames = dict;

    [self resetSearch];
    [table reloadData];
    [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO];
}
- (void)createThirtPartyTitleView
{
    topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CT_HEADER_SCREEN_WIDTH, 64)];
    topView.backgroundColor = CT_HEADER_WHITE_COLOR;
    [self.view addSubview:topView];
    
    //标题
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, CT_HEADER_SCREEN_WIDTH, 44)];
    titleLabel.font = [UIFont fontWithName:nil size:19];
    titleLabel.text = [CTAppLanguage localizedStringForKey:@"sectionsViewController_title_text" withValue:nil withTable:@"Language"];
    titleLabel.textColor = CT_HEADER_GREEN_COLOR;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:titleLabel];
    
    //取消
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(CT_HEADER_SCREEN_WIDTH-44,20 , 44, 44);
    [cancelButton addTarget:self action:@selector(clickLeftButton) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton setTitle:[CTAppLanguage localizedStringForKey:@"userAgreementViewControl_cancel_text" withValue:nil withTable:@"Language"] forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [cancelButton setTitleColor:CT_HEADER_GREEN_COLOR forState:UIControlStateNormal];
    [cancelButton setTitleColor:LOGINVIEW_USER_REGISTER_TEXT_HEIGHT_COLOR forState:UIControlStateHighlighted];
    [topView addSubview:cancelButton];
}
-(void)setAreaArray:(NSMutableArray*)array
{
    _areaArray=[NSMutableArray arrayWithArray:array];
}

#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [keys count];
    
}

- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return 0;
    
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    return [nameSection count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    
    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier ];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                       reuseIdentifier: SectionsTableIdentifier ];
    }
    
    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range=[str1 rangeOfString:@"+"];
    NSString* str2=[str1 substringFromIndex:range.location];
    NSString* areaCode=[str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryName=[str1 substringToIndex:range.location];

    cell.textLabel.text=countryName;
    cell.detailTextLabel.text=[NSString stringWithFormat:@"+%@",areaCode];
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView 
titleForHeaderInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return nil;
    NSString *key = [keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;
    
    return key;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (isSearching)
        return nil;
    return keys;
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView 
  willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [search resignFirstResponder];
    search.text = @"";
    isSearching = NO;
    [tableView reloadData];
    return indexPath;
}
- (NSInteger)tableView:(UITableView *)tableView 
sectionForSectionIndexTitle:(NSString *)title 
               atIndex:(NSInteger)index
{
    NSString *key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch)
    {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else return index;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSString *key = [keys objectAtIndex:section];
    NSArray *nameSection = [names objectForKey:key];
    
    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range=[str1 rangeOfString:@"+"];
    NSString* str2=[str1 substringFromIndex:range.location];
    NSString* areaCode=[str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryName=[str1 substringToIndex:range.location];

    CountryAndAreaCode* country=[[CountryAndAreaCode alloc] init];
    country.countryName=countryName;
    country.areaCode=areaCode;
    

    
    [self.view endEditing:YES];
    
    int compareResult = 0;
    
    
    for (int i=0; i<_areaArray.count; i++)
    {
        NSDictionary* dict1=[_areaArray objectAtIndex:i];
      
        [dict1 objectForKey:areaCode];
        NSString* code1 = [dict1 valueForKey:@"zone"];
        if ([code1 isEqualToString:areaCode])
        {
            compareResult=1;
            break;
        }
    }
    
//    if (!compareResult)
//    {
//        UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
//                                                      message:NSLocalizedString(@"doesnotsupportarea", nil)
//                                                     delegate:self
//                                            cancelButtonTitle:NSLocalizedString(@"sure", nil)
//                                            otherButtonTitles:nil, nil];
//        [alert show];
//        return;
//    }
    
    //传递数据
    if ([self.delegate respondsToSelector:@selector(setSecondData:)]) {
        [self.delegate setSecondData:country];
    }
    
    //关闭当前
    [self clickLeftButton];
}

#pragma mark -
#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSString *searchTerm = [searchBar text];
    [self handleSearchForTerm:searchTerm];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    isSearching = YES;
    [table reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar 
    textDidChange:(NSString *)searchTerm
{
    if ([searchTerm length] == 0)
    {
        [self resetSearch];
        [table reloadData];
        return;
    }
    
    [self handleSearchForTerm:searchTerm];
    
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    isSearching = NO;
    search.text = @"";

    [self resetSearch];
    [table reloadData];
    
    [searchBar resignFirstResponder];
}

-(void)clickLeftButton
{
    [self dismissViewControllerAnimated:YES completion:^{
        ;
    }];
}

-(NSMutableDictionary *)mutableDeepCopy:(NSDictionary *)targetDic
{
    NSMutableDictionary *ret = [[NSMutableDictionary alloc] initWithCapacity:[targetDic count]];
    NSArray * mkeys = [targetDic allKeys];
    for (id key in mkeys)
    {
        id oneValue = [targetDic valueForKey:key];
        id oneCopy = nil;
        
        if ([oneValue respondsToSelector:@selector(mutableDeepCopy:)])
            oneCopy = [oneValue mutableDeepCopy:targetDic];
        else if ([oneValue respondsToSelector:@selector(mutableCopy)])
            oneCopy = [oneValue mutableCopy];
        if (oneCopy == nil)
            oneCopy = [oneValue copy];
        [ret setValue:oneCopy forKey:key];
    }
    return ret;
}

@end
